package org.ruanjj.addtwonumbers;

import org.ruanjj.linkedlist.ListNode;

import java.awt.*;

/*
* 输入：(6 -> 1 -> 7) + (2 -> 9 -> 5)，即617 + 295
   输出：9 -> 1 -> 2，即912
* */
public class Solution {
    int count = 0;
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        l1 = reverseList(l1);
        l2 = reverseList(l2);

        if(l1 == null && l2 == null){
            return null;
        }

        return add(l1,l2);
    }

    //反转链表
    private ListNode reverseList(ListNode head){
       //递归
        ListNode cur = new ListNode(-1);
        ListNode pre = cur;
        if(head == null){
            return head;
        }
        cur.next = reverseList(head.next);
        while(cur.next != null){
            cur = cur.next;
        }
        cur.next = head;
        cur = cur.next;
        cur.next = null;
        return pre.next;
    }

    private ListNode add(ListNode l1, ListNode l2){
        ListNode cur = new ListNode(-1);
        ListNode pre = cur;
        if(l1 == null && l2 == null){
            return null;
        }
        int val1 = l1 == null? 0: l1.val;
        int val2 = l2 == null? 0: l2.val;
        int val = val1+val2+count;
        count = val/10 > 0? val/10:0;
        ListNode tmp = new ListNode(val%10);
        if(l1 == null){
            cur.next = add(null,l2.next);
        }else if(l2 == null){
            cur.next = add(l1.next,null);
        }else{
            cur.next = add(l1.next,l2.next);
        }
        while(cur.next != null){
            cur = cur.next;
        }
        cur.next = tmp;
        return pre.next;
    }
}
